package middleware

import (
	"easyShop/services"
	"github.com/gin-gonic/gin"
	"strings"
)

func UserAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 请求前...
		authorization := c.GetHeader("Authorization")
		if authorization == "" {
			c.AbortWithStatusJSON(200, gin.H{
				"code":    401,
				"message": "Token is invalid",
				"data":    nil,
			})
			return
		}

		token := strings.ReplaceAll(authorization, "Bearer ", "")

		dataOfJwt, encodeErr := services.JwtDecode(token)

		if encodeErr != nil || len(dataOfJwt) == 0 || dataOfJwt["userInfo"] == nil {
			c.AbortWithStatusJSON(200, gin.H{
				"code":    401,
				"message": "Token is invalid",
				"data":    nil,
			})
			return
		}

		c.Set("userInfo", dataOfJwt["userInfo"])

		// next
		c.Next()

		// 请求后...

		// 获取发送的 status
		//status := c.Writer.Status()
	}
}
